import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/shift/current_shift_entity.dart';
import 'package:flutter_deer/database/database_manager.dart';
import 'package:flutter_deer/database/order_status.dart';
import 'package:flutter_deer/database/tables.dart';
import 'package:flutter_deer/dl/dl.dart';
import 'package:flutter_deer/mvvm/loading_dialog.dart';
import 'package:flutter_deer/objectbox.g.dart';
import 'package:flutter_deer/res/dimens.dart';
import 'package:flutter_deer/ui/cashier/provider/cashier_page_provider.dart';
import 'package:flutter_deer/ui/cashier/provider/common_http_provider.dart';
import 'package:flutter_deer/ui/cashier/provider/fcc_provider.dart';
import 'package:flutter_deer/ui/cashier/provider/mqtt_provider.dart';
import 'package:flutter_deer/util/socket/mdc_provider.dart';
import 'package:flutter_deer/util/speak/tts_manger.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/util/user_config_manager.dart';
import 'package:flutter_deer/widgets/dialog/abandon_order_dialog.dart';
import 'package:flutter_deer/widgets/my_refresh_list.dart';
import 'package:flutter_deer/widgets/press_blue_button.dart';
import 'package:flutter_deer/widgets/select_left_home_widget.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:get/get.dart';
import 'package:rxdart/rxdart.dart';

import 'dialog/match_pre_pay_list_dialog.dart';
import 'item/cashier_item_left.dart';

class CashierPageLeftOilList extends StatefulWidget {
  const CashierPageLeftOilList({super.key});

  @override
  _CashierPageLeftOilListState createState() => _CashierPageLeftOilListState();
}

class _CashierPageLeftOilListState extends State<CashierPageLeftOilList> with AutomaticKeepAliveClientMixin<CashierPageLeftOilList>, SingleTickerProviderStateMixin {
  final List<AppOrderBean> _list = [];
  final _scrollController = ScrollController();
  final mProvider = Get.find<CashierPageProvider>();
  final mFccProvider = Get.find<FccProvider>();
  final mdcProvider = Get.find<MdcProvider>();
  final mqttProvider = Get.find<MqttProvider>();
  final commonHttpProvider = Get.find<CommonHttpProvider>();
  final _tts = Get.find<TtsEngineManager>();
  final List<int> _numberOptions = [];

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 初始化数据
      _handleHubOrderData();
      // 初始化零Tube
      commonHttpProvider.getZeroTube();
      // 初始化MDC
      mdcProvider.orderStream.listen((event) {
        mFccProvider.uploadOrderListSingle(event);
      });
      // 循环上传订单
      mFccProvider.startUploadOrderCycle();
      // mqtt
      mqttProvider.initMqtt();
      // 初始化语音播报
      _tts.registerEngine();
    });


    UserConfigManager.getOilGuns().forEach((oils) {
      oils.shelfList?.forEach((shelf) {
        _numberOptions.add(shelf.shelfNo ?? 0);
      });
    });
  }

  late ObjectIdBox _objectIdBox;
  late StreamSubscription<dynamic> _subscription;

  // 处理集线器订单数据
  Future<void> _handleHubOrderData() async {
    //监听数据库变化
    _objectIdBox = getIt<ObjectIdBox>();
    final Store store = await _objectIdBox.storeAsync; // 等待初始化完成
    _subscription = store
        .box<AppOrderBean>()
        .query()
        .watch(triggerImmediately: false)
        .debounceTime(const Duration(milliseconds: 800)) // 防抖 300ms
        .listen((changes) {
      print('[pageLeftTag] 数据库变化[AppOrderBean] 800ms');
      _onRefresh();
    });
    _onRefresh();
  }

  // 刷新条件 枪号 时间
  int _selectedNumber = 0;
  String _selectedTime = '';

  /// [处理左侧订单列表数据]
  /// 1、合单
  /// 2、未支付
  /// 3、已销单
  /// 按时间排序
  void _loadLeftOrderList({bool refresh = false}) {
    if (refresh) {
      _pageIndex = 1;
    } else {
      if (!_hasMore) return; // 已加载完所有数据，不再请求
      _pageIndex++;
    }

    // 构建基础查询条件
    var queryCondition = (AppOrderBean_.shiftNo.equals(CurrentShiftEntity.get()?.workCycleCode ?? '')) &
        (AppOrderBean_.suspendTime.equals('')) &
        (AppOrderBean_.energyOrderStatus.lessThan(OrderOilStatus.DONE));

    // 如果枪号不为0，则添加枪号查询条件
    if (_selectedNumber != 0) {
      queryCondition = queryCondition & (AppOrderBean_.nzl.equals(_selectedNumber));
    }

    // 如果时间不为空，则添加时间查询条件
    if (_selectedTime.isNotEmpty) {
      // 获取当前系统时间戳LONG 精确到秒
      final _now = DateTime.now().millisecondsSinceEpoch;
      final _min = int.parse(_selectedTime.replaceAll('min', '')) * 60 * 1000;
      final p = _now - _min;
      print('[pageLeftTag] _loadLeftOrderList p:$p');
      // p 时间戳 秒 转为 可以2025年8月29日 16:08:27
      final pDate = DateTime.fromMillisecondsSinceEpoch(p);
      print('[pageLeftTag] -----------> _loadLeftOrderList pDate:$pDate');
      queryCondition = queryCondition & (AppOrderBean_.mdcOrderTime.greaterThan(p));
    }

    // 构建最终查询
    final Query<AppOrderBean> query = _objectIdBox.store
        .box<AppOrderBean>()
        .query(queryCondition)
        .order(AppOrderBean_.energyOrderStatus, flags: Order.descending)
        .order(AppOrderBean_.mdcOrderTime, flags: Order.descending)
        .build();

    query.offset = (_pageIndex - 1) * 10;
    query.limit = 10;
    final result = query.find();
    print('[pageLeftTag] _loadLeftOrderList result: _pageIndex:${_pageIndex} size=${result.length} result first:${result.firstOrNull?.mny}');
    query.close();
    if (!mounted) return; // 避免在未挂载的页面上调用 setState
    if (_pageIndex == 1) {
      setState(() {
        _list.clear();
        _list.addAll(result);
        _hasMore = result.length == 10;
        print('[pageLeftTag] setState: _pageIndex:${_pageIndex} size=${result.length} _list first:${_list.firstOrNull?.mny}');
      });
      if (_scrollController.hasClients) {
        // _scrollController.jumpTo(0); // 立即回到顶部
        print('[pageLeftTag] jumpTo(0):${_pageIndex} size=${result.length}');
      }
    } else {
      setState(() {
        _list.addAll(result);
        _hasMore = result.length == 10;
      });
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _subscription.cancel();
    _objectIdBox.dispose();
    super.dispose();
  }

  Future<dynamic> _onRefresh() async {
    print('[pageLeftTag] onRefresh $_pageIndex  ${_list.length}');
    _loadLeftOrderList(refresh: true);
  }

  Future<dynamic> _loadMore() async {
    print('[pageLeftTag] loadMore $_pageIndex  ${_list.length}');
    _loadLeftOrderList(refresh: false);
  }

  int _pageIndex = 0;
  bool _hasMore = true;
  StateType _stateType = StateType.order;

  // 这里要实现局部刷新
  // 1、是否上传
  // 2、价格异常
  // 3、状态
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Stack(
      children: [
        // 列表部分使用Expanded充满剩余空间
        Positioned(
          top: 40,
          left: 0,
          right: 0,
          bottom: 0,
          child: DeerListView(
            controller: _scrollController,
            itemCount: _list.length,
            stateType: _stateType,
            onRefresh: _onRefresh,
            loadMore: _loadMore,
            hasMore: _hasMore,
            itemBuilder: (_, index) {
              final String heroTag = 'goodsImg${widget.hashCode}-$index';
              final item = _list[index];
              return CashierOilItemLeft(
                heroTag: heroTag,
                item: item,
                index: index,
                onTapMenu: () {
                  showDialog<void>(
                    context: context,
                    builder: (context) {
                      return AlertDialog(
                        title: const Text('油单操作'),
                        content: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            const SizedBox(height: 5),
                            PressBlueButton(height: 40, fontSize: Dimens.font_sp18, text: '匹配', onPressed: () => _showMatchPrePayListDialog(item)),
                            const SizedBox(height: 5),
                            PressBlueButton(height: 40, fontSize: Dimens.font_sp18, text: '解锁', onPressed: () => _unlockOrder(item)),
                            const SizedBox(height: 5),
                            PressBlueButton(height: 40, fontSize: Dimens.font_sp18, text: '弃单', onPressed: () => _showAbandonOrderDialog(item, index)),
                            // const SizedBox(height: 5),
                            // PressBlueButton(height: 40, fontSize: Dimens.font_sp18, text: '合并', onPressed: () => () {}),
                          ],
                        ),
                      );
                    },
                  );
                },
                onTapItemClick: () {
                  mProvider.selectOilItem(item, clear: true);
                  mFccProvider.uploadOrderListSingle(item);
                },
              );
            },
          ),
        ),
        // 选择框固定在顶部
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          child: SelectionWidget(
            numberOptions: _numberOptions,
            onSelectionChanged: (number, time) {
              print('选择了 [$number] [$time]');
              _selectedNumber = number;
              _selectedTime = time;
              _loadLeftOrderList(refresh: true);
            },
          ),
        ),
      ],
    );
  }

  // 展示匹配油单弹窗
  void _showMatchPrePayListDialog(AppOrderBean item) {
    Get.back<void>();
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return MatchPrePayListDialog(defaultSelectedEnergyOrderIds: item.energyOrderId);
      },
    );
  }

  // 解锁油单
  void _unlockOrder(AppOrderBean item) {
    mProvider.requestUnlockOrder(item.energyOrderId, onSuccessCallBack: () {
      Get.back<void>();
    });
  }

  // 展示弃单
  void _showAbandonOrderDialog(AppOrderBean item, int index) {
    Get.back<void>();
    showDialog<void>(
      context: context,
      builder: (context) {
        return AbandonOrderDialog(
          order: item,
          onConfirm: (String input, int code) {
            mProvider.giveUpOrder(
              item,
              code,
              reason: input,
              onSuccess: (msg) {
                setState(() {
                  _list.removeAt(index);
                  if (_list.isEmpty) {
                    _stateType = StateType.goods;
                  }
                });
                Toast.show('弃单成功');
              },
              onError: (msg) {
                showInfoDialog(title: '弃单失败', content: msg);
              },
            );
          },
        );
      },
    );
  }

  @override
  bool get wantKeepAlive => true;
}
